<!-- 产品产量 -->
<template>
  <div class="energy-performance-wrap">
    <px-form ref="formRef" :model="queryParams" :inline="true" class="search-form">
      <px-form-item label="时间范围" prop="dateRange">
        <px-date-picker
          v-model="queryParams.dateRange"
          type="monthrange"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          value-format="YYYY-MM"
        />
      </px-form-item>
      <div class="search-form-btn">
        <px-button type="primary" @click="handleQuery">查询</px-button>
        <px-button @click="resetQuery">重置</px-button>
        <px-button v-has="'ALL_ENERGY_PERFORMANCE_PRODUCT_OUTPUT_ADD'" type="primary" @click="handleAdd">新增</px-button>
      </div>
    </px-form>
    <div v-loading="tableLoading" class="table-content">
      <px-table height="calc(100vh - 300px)" :data="tableData" size="small" border class="common-table">
        <px-table-column type="index" label="序号" fixed width="55" align="center" />
        <px-table-column prop="year" label="年度" min-width="120" show-overflow-tooltip />
        <px-table-column prop="cycle" label="周期" min-width="120" show-overflow-tooltip />
        <px-table-column prop="production" label="产量" min-width="120" show-overflow-tooltip />
        <px-table-column prop="factoryName" label="厂区" min-width="120" show-overflow-tooltip />
        <px-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <px-tooltip content="编辑" placement="top">
              <px-button v-has="'ALL_ENERGY_PERFORMANCE_PRODUCT_OUTPUT_EDIT'" link icon="EditPen" type="primary" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button v-has="'ALL_ENERGY_PERFORMANCE_PRODUCT_OUTPUT_DELETE'" link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        class="table-pagination"
        :total="total"
        @pagination="handleQuery"
      />
    </div>
    <!-- 编辑、新增弹框 -->
    <px-dialog v-model="dialogAddModelVisible" :title="dialogTitle" width="460">
      <px-form ref="addModelRef" :model="addQueryParams" :rules="rules" label-position="right" label-width="100px">
        <!-- <px-form-item label="厂区" prop="factory">
            <px-select v-model="facCode" placeholder="请选择厂区" clearable>
              <px-option v-for="item in facList" :key="item.id" :label="item.name" :value="item.value" />
            </px-select>
          </px-form-item> -->
        <px-form-item label="日期" prop="date">
          <px-date-picker
            v-model="addQueryParams.date"
            type="month"
            placeholder="请选择月份"
            value-format="YYYY-MM-DD"
            clearable
            style="width: 300px"
          />
        </px-form-item>
        <px-form-item label="产量" prop="production">
          <px-input-number
            v-model="addQueryParams.production"
            maxlength="6"
            :max="500000"
            style="width: 300px"
            placeholder="请输入产量(最大值是500000)"
            clearable
            @input="validateInput"
          />
        </px-form-item>
      </px-form>
      <template #footer>
        <div>
          <px-button @click="dialogAddModelVisible = false">取消</px-button>
          <px-button type="primary" @click="handleAddModel">保存</px-button>
        </div>
      </template>
    </px-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, toRefs, computed } from "vue";
import { delOutputAPI, listOutputAPI, updateOutputAPI } from "@/api/energy/performance";
import dayjs from "dayjs";
import { PxMessage } from "px-ui";

defineOptions({
  name: "ALL_ENERGY_PERFORMANCE_PRODUCT_OUTPUT"
});

const formRef = ref();
const addModelRef = ref(null);

const state = reactive({
  queryParams: {
    dateRange: ""
  },
  tableLoading: false,
  tableData: [],
  total: 0,
  pageNum: 1,
  pageSize: 20,
  dialogAddModelVisible: false,
  dialogTitle: "编辑",
  addQueryParams: {
    factory: "",
    production: "",
    date: ""
  }
});
const { queryParams, tableLoading, tableData, total, pageNum, pageSize, dialogAddModelVisible, dialogTitle, addQueryParams } = toRefs(state);

const rules = computed(() => ({
  date: [{ required: true, message: "日期不能为空", trigger: "change" }],
  production: [{ required: true, message: "产量不能为空", trigger: "blur" }]
}));

// 获取系统中的统一的厂区，下拉框处理
const facCode = ref(localStorage.getItem("facCode"));
const tempFacList = JSON.parse(localStorage.getItem("facList"));
const facList = tempFacList?.filter(item => facCode.value === item.code) || [];
onMounted(() => {
  initQuery();
  handleQuery();
});

// 获取列表的数据
const getTableList = async () => {
  try {
    state.tableLoading = true;
    let dateRange = state.queryParams.dateRange;
    let startTime = "";
    let endTime = "";
    if (dateRange?.[0]) {
      startTime = dateRange?.[0] + "-01 00:00:00";
    }
    if (dateRange?.[1]) {
      endTime = dayjs(dateRange?.[1]).endOf("month").format("YYYY-MM-DD") + " 23:59:59";
    }
    let params = {
      dimension: "MONTH",
      startDate: startTime || "",
      endDate: endTime || "",
      pageNum: state.pageNum,
      pageSize: state.pageSize
    };
    const res = await listOutputAPI(params);
    let arr = [];
    let resData = res?.data || [];
    if (resData && resData.length) {
      resData.forEach(v => {
        v["year"] = v.month.substring(0, 4) + "年";
        v["cycle"] = v.month.substring(5, 7) + "月";
        v["factoryName"] = tempFacList?.find(i => i.code === v.factory)?.name || "";
      });
    }
    state.tableData = resData;
    state.total = res?.total || 0;
  } catch (error) {
    console.log(error);
  } finally {
    state.tableLoading = false;
  }
};
const validateInput = (val, val2) => {
  let num = val.replace(/\D/g, "");
  if (num && Number(num) > 500000) {
    num = 500000;
  }
  state.addQueryParams.production = num;
};
// 默认查询条件
const initQuery = () => {
  // state.queryParams.dateRange = [dayjs().subtract(1, "year").format("YYYY-MM"), dayjs().format("YYYY-MM")];
  state.queryParams.factory = state.factoryList?.[0]?.value || "";
  state.addQueryParams.factory = state.factoryList?.[0]?.value || "";
};
const handleQuery = () => {
  getTableList();
};
const handleAdd = () => {
  state.dialogAddModelVisible = true;
  state.dialogTitle = "新增";
  state.addQueryParams.date = "";
  state.addQueryParams.production = "";
};
const resetQuery = () => {
  formRef.value.resetFields();
  initQuery();
  handleQuery();
};
const handleEdit = row => {
  state.dialogTitle = "编辑";
  state.dialogAddModelVisible = true;
  state.addModelForm = [row];
  state.addQueryParams.date = row?.month?.substring(0, 10) || "";
  state.addQueryParams.production = row?.production || "";
};
// 删除
const handleDelete = row => {
  delOutputAPI({ id: row.id }).then(res => {
    PxMessage.success("提交成功");
    handleQuery();
  });
};
// 编辑
const handleAddModel = () => {
  addModelRef.value.validate(validate => {
    if (validate) {
      if (state.dialogTitle === "编辑") {
        let data = state.addModelForm[0] || {};
        let { id, factory } = data;
        let month = state.addQueryParams.date + " 00:00:00";
        let production = state.addQueryParams.production;
        let params = {
          id: id,
          month: month,
          production: production,
          factory: factory
        };
        updateOutputAPI(params)
          .then(res => {
            if (res) {
              PxMessage.success("修改成功");
              handleQuery();
            }
          })
          .finally(() => {
            state.dialogAddModelVisible = false;
          });
      } else {
        let params = {
          factory: state.addQueryParams.factory,
          month: state.addQueryParams.date + " 00:00:00",
          production: Number(state.addQueryParams.production)
        };
        updateOutputAPI(params)
          .then(res => {
            if (res) {
              PxMessage.success("新增成功");
              handleQuery();
            }
          })
          .finally(() => {
            state.dialogAddModelVisible = false;
          });
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.energy-performance-wrap {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: calc(100vh - 133px);
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
}

.search-form {
  display: flex;
  align-items: center;

  .search-form-btn {
    margin-bottom: 16px;
  }
}

.add-form-wrap {
  display: flex;
  justify-content: center;
}
</style>
